package StudentSystem2;

import java.io.*;
import java.util.Scanner;

/**
 * 代码提升：
 * 1：不会改变的常量设置成static final类型
 * 2：多用try……catch
 * 3：字符串的输入最好用nextLine，但是如果需要吸收换行符，则需再写一个nextLine
 * 4：String.equalsIgnoreCase("")    这个方法底层是一个三元表达式，若字符串内容与括号内容相同，则返回true，否则返回false，完美解决了运算外的三元符号的需求
 * 5：System.arraycopy方法，可以实现，同一个类的数组里元素的移动(从那个数组，那个索引，到哪个数组，哪个索引开始，移动几个)
 * 总结：成熟的代码风格
 * 在方法体中，成熟的代码风格总是先把不满足条件的进行处理，然后剩下的是满足条件的，再处理
 * 有关输入语句，如果是String类型的，就使用nextLine来读取，后续再对这个字符串进行处理
 * 在复杂的程序中，try……catch包裹着输入语句和程序复杂的处理
 * 对于在程序中没有改变过，但是可以根据自己需求用途改变的变量，都设置为static final类型在main方法外
 * 能用包装好的方法代替的代码，就用方法来实现，减少基本语句的使用
 */
public class Main {
    private static final int INITIAL_SIZE = 5;//使用常量，提高代码可变性和整体性
    private static final String FILE_PATH = "C:\\Users\\和靖皓\\Desktop\\学生信息系统.txt";
    private static final String BACKUP_PATH = "C:\\Users\\和靖皓\\Desktop\\学生信息系统备份.txt";
//把代码中不会再改变的设置成常量
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Student[] students = new Student[INITIAL_SIZE];
        int num = 0;

        while (true) {
            menu();
            try {
                int choice = sc.nextInt();
                sc.nextLine(); // 消耗换行符

                switch (choice) {
                    case 1:
                        num = addStudent(students, num, sc);
                        break;
                    case 2:
                        num = removeStudent(students, num, sc);
                        break;
                    case 3:
                        modifyStudent(students, num, sc);
                        break;
                    case 4:
                        findStudent(students, num, sc);
                        break;
                    case 5:
                        num = importFromFile(students, num);
                        break;
                    case 6:
                        exportToFile(students, num);
                        break;
                    case 7:
                        System.out.println("感谢使用学生管理系统，再见！");
                        return;
                    default:
                        System.out.println("输入错误，请重新输入1-7的数字");
                }
            } catch (Exception e) {
                System.out.println("发生错误: " + e.getMessage());
                sc.nextLine(); // 清除错误输入
            }
        }
    }

    private static void menu() {
        System.out.println("\n---------学生管理系统-----------");
        System.out.println("1. 添加学生信息");
        System.out.println("2. 删除学生信息");
        System.out.println("3. 修改学生信息");
        System.out.println("4. 查询学生信息");
        System.out.println("5. 从文件导入学生信息");
        System.out.println("6. 导出学生信息到文件");
        System.out.println("7. 退出系统");
        System.out.print("请选择操作(1-7): ");
    }

    private static int addStudent(Student[] students, int num, Scanner sc) {
        while (true) {
            if (num >= students.length) {
                students = expandArray(students);
            }

            try {
                System.out.println("\n请依次输入学生的学号、姓名、年龄、家庭住址（以空格分隔）:");
                String[] input = sc.nextLine().split(" ");

                if (input.length < 4) {
                    System.out.println("输入格式不正确，请按格式输入");
                    continue;
                }

                int id = Integer.parseInt(input[0]);
                String name = input[1];
                int age = Integer.parseInt(input[2]);
                String address = input[3];

                students[num] = new Student(id, name, age, address);
                num++;
                System.out.println("学生信息添加成功！");

                System.out.print("是否继续添加？(y/n): ");
                if (!sc.nextLine().equalsIgnoreCase("y")) {
                    return num;
                }
            } catch (NumberFormatException e) {
                System.out.println("学号和年龄必须是数字，请重新输入");
            }
        }
    }

    private static int removeStudent(Student[] students, int num, Scanner sc) {
        if (num <= 0) {
            System.out.println("当前没有学生信息可删除");
            return num;
        }

        while (true) {
            System.out.print("\n请输入要删除的学生学号: ");
            int id;
            try {
                id = Integer.parseInt(sc.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的学号数字");
                continue;
            }

            int index = findStudentIndex(students, num, id);
            if (index == -1) {
                System.out.println("未找到该学号的学生");
            } else {
                // 将后面的元素前移
                System.arraycopy(students, index + 1, students, index, num - index - 1);
                students[num - 1] = null; // 清除最后一个引用
                num--;
                System.out.println("学生信息删除成功！");
            }

            System.out.print("是否继续删除？(y/n): ");
            if (!sc.nextLine().equalsIgnoreCase("y")) {
                return num;
            }
        }
    }

    private static void modifyStudent(Student[] students, int num, Scanner sc) {
        if (num <= 0) {
            System.out.println("当前没有学生信息可修改");
            return;
        }

        while (true) {
            System.out.print("\n请输入要修改的学生学号: ");
            int id;
            try {
                id = Integer.parseInt(sc.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的学号数字");
                continue;
            }

            int index = findStudentIndex(students, num, id);
            if (index == -1) {
                System.out.println("未找到该学号的学生");
            } else {
                System.out.println("当前学生信息: " + students[index]);
                System.out.println("请选择要修改的内容:");
                System.out.println("1. 姓名");
                System.out.println("2. 年龄");
                System.out.println("3. 家庭住址");
                System.out.println("4. 全部信息");
                System.out.print("请选择(1-4): ");

                try {
                    int choice = Integer.parseInt(sc.nextLine());
                    switch (choice) {
                        case 1:
                            System.out.print("请输入新的姓名: ");
                            students[index].setName(sc.nextLine());
                            break;
                        case 2:
                            System.out.print("请输入新的年龄: ");
                            students[index].setAge(Integer.parseInt(sc.nextLine()));
                            break;
                        case 3:
                            System.out.print("请输入新的家庭住址: ");
                            students[index].setAddress(sc.nextLine());
                            break;
                        case 4:
                            System.out.println("请依次输入新的学号、姓名、年龄、家庭住址（以空格分隔）:");
                            String[] input = sc.nextLine().split(" ");
                            if (input.length >= 4) {
                                students[index].setId(Integer.parseInt(input[0]));
                                students[index].setName(input[1]);
                                students[index].setAge(Integer.parseInt(input[2]));
                                students[index].setAddress(input[3]);
                            }
                            break;
                        default:
                            System.out.println("无效选择");
                    }
                    System.out.println("修改成功！");
                } catch (NumberFormatException e) {
                    System.out.println("输入无效，请重新操作");
                }
            }

            System.out.print("是否继续修改？(y/n): ");
            if (!sc.nextLine().equalsIgnoreCase("y")) {
                return;
            }
        }
    }

    private static void findStudent(Student[] students, int num, Scanner sc) {
        if (num <= 0) {
            System.out.println("当前没有学生信息可查询");
            return;
        }

        while (true) {
            System.out.print("\n请输入要查询的学生学号: ");
            int id;
            try {
                id = Integer.parseInt(sc.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的学号数字");
                continue;
            }

            int index = findStudentIndex(students, num, id);
            if (index == -1) {
                System.out.println("未找到该学号的学生");
            } else {
                System.out.println("查询结果:");
                System.out.println(students[index]);
            }

            System.out.print("是否继续查询？(y/n): ");
            if (!sc.nextLine().equalsIgnoreCase("y")) {
                return;
            }
        }
    }

    private static int importFromFile(Student[] students, int num) {
        try (BufferedReader br = new BufferedReader(new FileReader(FILE_PATH))) {
            String line;
            while ((line = br.readLine()) != null && line.trim().length() > 0) {
                if (num >= students.length) {
                    students = expandArray(students);
                }

                String[] parts = line.split(" ");
                if (parts.length >= 4) {
                    try {
                        students[num] = new Student(
                                Integer.parseInt(parts[0]),
                                parts[1],
                                Integer.parseInt(parts[2]),
                                parts[3]
                        );
                        num++;
                    } catch (NumberFormatException e) {
                        System.out.println("文件格式错误，跳过行: " + line);
                    }
                }
            }
            System.out.println("成功导入 " + num + " 条学生记录");
        } catch (IOException e) {
            System.out.println("导入文件时出错: " + e.getMessage());
        }
        return num;
    }

    private static void exportToFile(Student[] students, int num) {
        if (num <= 0) {
            System.out.println("没有学生信息可导出");
            return;
        }

        try (BufferedWriter bw = new BufferedWriter(new FileWriter(BACKUP_PATH))) {
            for (int i = 0; i < num; i++) {
                bw.write(students[i].getId() + " " +
                        students[i].getName() + " " +
                        students[i].getAge() + " " +
                        students[i].getAddress());
                bw.newLine();
            }
            System.out.println("成功导出 " + num + " 条学生记录到文件");
        } catch (IOException e) {
            System.out.println("导出文件时出错: " + e.getMessage());
        }
    }

    private static int findStudentIndex(Student[] students, int num, int id) {
        for (int i = 0; i < num; i++) {
            if (students[i].getId() == id) {
                return i;
            }
        }
        return -1;
    }

    private static Student[] expandArray(Student[] students) {
        Student[] newArray = new Student[students.length * 2];
        System.arraycopy(students, 0, newArray, 0, students.length);
        System.out.println("数组已扩容，新容量: " + newArray.length);
        return newArray;
    }
}
